package com.xsoft.permission;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.xsoft.common.util.ApplicationUtils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import androidx.fragment.app.FragmentActivity;
import io.reactivex.functions.Consumer;

/**
 * created by zhangkai on 2020/6/3
 * email: 405547628@qq.com
 * desc: 权限申请统一处理
 */
@Aspect
public class PermissionAspectJ {
    @Around("execution(@com.xsoft.permission.Permission * *(..)) && @annotation(permission)")
    public void checkPermission(final ProceedingJoinPoint joinPoint, final Permission permission) {
        Log.i("PermissionAspectJ", "checkPermission");
        Activity activity = ApplicationUtils.getTopActivity();
        if (activity instanceof FragmentActivity) {
            RxPermissions rxPermissions = new RxPermissions((FragmentActivity) activity);
            rxPermissions.request(permission.value())
                    .subscribe(new Consumer<Boolean>() {

                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            if (aBoolean || permission.keepGoing()) {
                                try {
                                    joinPoint.proceed();
                                } catch (Throwable throwable) {
                                    throwable.printStackTrace();
                                    Log.e("permission", throwable.getMessage());
                                }
                            } else {
                                Toast.makeText(ApplicationUtils.getTopActivity().getApplicationContext(),
                                        "请先授权", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        } else {
            throw new NullPointerException("请使用androidx.fragment.app.FragmentActivity");
        }
    }
}
